package com.dfbz.service.impl;

import com.dfbz.dao.DeptDao;
import com.dfbz.model.Dept;
import com.dfbz.service.DeptService;

import java.util.*;

public class DeptServiceImpl implements DeptService {
    DeptDao deptDao=new DeptDao();
    @Override
    public Dept findById(Integer id) {
        return deptDao.findByid(id);
    }

    @Override
    public ArrayList<Dept> findList() {
        return deptDao.findList();
    }

    @Override
    public void save(Dept dept) {
        deptDao.save(dept);
    }

    @Override
    public void deleteById(Integer id) {
        deptDao.deleteById(id);
    }

    @Override
    public void update(Dept dept) {
        deptDao.update(dept);
    }

    @Override
    public List<Map<String, Object>> findAll() {
        List<Map<String,Object>> results=new ArrayList<>();
        Map<String,Object> deptMap;
        Set<String> deptIds=new HashSet<>();
        List<Map<String, Object>> all = deptDao.findAll();
        for (Map<String,Object> map:all) {
            deptMap=new HashMap<>();
            String deptId = map.get("deptId").toString();
            String deptName = map.get("deptName").toString();
            if (!deptIds.contains(deptId)){
                deptMap.put("deptId",deptId);
                deptMap.put("deptName",deptName);
                results.add(deptMap);
                deptIds.add(deptId);
            }
        }
        for (Map<String,Object> dept:results) {
            List<Map<String,Object>> userList=new ArrayList<>();
            String deptId=dept.get("deptId").toString();
            for (Map<String,Object> map:all) {
                String deptId2=map.get("deptId").toString();
                if (deptId.equals(deptId2)){
                    if (null != map.get("uId")){
                        userList.add(map);
                    }
                }
            }
            dept.put("userList",userList);
            dept.put("count",userList.size());
        }
        return results;
    }
}
